package com.ts.proj.json;


import com.alibaba.fastjson.JSONArray;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.common.domain.RemoteResult;
import com.ts.proj.entity.*;
import com.ts.proj.entity.excelEntity.CarEntityExcel;
import com.ts.proj.service.CarService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.proj.service.SystemConstantService;
import com.ts.proj.service.TransportunitService;
import com.ts.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

//说明 字符串：Car，作为替换字符串 LOWERCar

@RestController
@Slf4j
public class CarJson extends BaseController{

    @Autowired
    private TransportunitService transportunitService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CarService carService;

    @Autowired
    private SystemConstantService systemConstantService;

    @Value("${restful.url}")
    private String url ;

    @Value("${restful.get-car}")
    private String getCar;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/car-list/{page}/{size}")
    public Map<String,Object> carList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){

        PageData param = new PageData();
        PageData pageData = this.getPageData();
        param.put("deleteFlag", "N");
        if(null!=pageData.get("carId")&&!"".equals(pageData.get("carId").toString())){
            param.put("carId", pageData.get("carId").toString());
        }
        long count = carService.count(param);
        List<CarEntity> cars = carService.findAll(param,page-1,size);
        param.put("total",count);
        param.put("rows", cars);
        return param;
    }

    @RequestMapping("/car-combobox-list")
    public Object adminGetRoleList(){
        List<PageData> pageDataList = new ArrayList<PageData>();
        PageData tempPa = new PageData();
        tempPa.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<CarEntity> carEntities = carService.findAll(tempPa);
        for(CarEntity carEntity : carEntities){
            PageData pd = new PageData();
            pd.put("value",carEntity.getCarId());
            pd.put("text",carEntity.getCarId());
            pageDataList.add(pd);
        }
        return JSONArray.toJSONString(pageDataList);
    }
    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/car-ins-upd-del/{id}")
    public String carInsUpdDel(@PathVariable("id") String id){
        PageData pageData = this.getPageData();
        PageData temp = new PageData();
        CarEntity car = carService.findById(Integer.valueOf(id));
        if("-2".equals(id)){
            if(null!=pageData.get("carId")&&!"".equals(pageData.getString("carId"))){
                temp.put("deleteFlag", "N");
                temp.put("carIdUnique", pageData.getString("carId").trim());
                List<CarEntity> all = carService.findAll(temp);
                if(all.size()==1){
                    car = all.get(0);
                }
            }
            //维护承运单位
            try{
                PageData unitPd = new PageData();
                unitPd.put("transportName", pageData.getString("transportUnit"));
                unitPd.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
                List<TransportunitEntity> all = transportunitService.findAll(unitPd);
                if(0==all.size()&&!"".equals(pageData.getString("transportUnit"))){
                    TransportunitEntity tEntity = new TransportunitEntity();
                    tEntity.setTransportName(pageData.getString("transportUnit"));
                    tEntity.setTransportUnit(PinyinHelperUtil.getPinYinHeadChar(pageData.getString("transportUnit")));
                    tEntity.setTransportPY(PinyinHelperUtil.getPinYinHeadChar(pageData.getString("transportUnit")));
                    transportunitService.save(tEntity);
                }
            }catch (Exception e){

            }

        }
        List<String> strings = EntityAttributeUtil.entityAttribute(CarEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
        for(String attr :strings){
            //字段信息维护

            if(null!=pageData.get(attr)){
//                log.info(attr);
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = CarEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().equals("set"+StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
//                            log.info(returnType[0].getName());
                            if (returnType[0].getName().equals("double")){
                                method.invoke(car, Double.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(car, pageData.getString(attr));

                            }
                        }
						if(method.getName().equals("setUserId")){
                            car.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            car.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            car.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        CarEntity save = carService.save(car);
        return String.valueOf(save.getCareWeight());
    } 
	@RequestMapping("/car-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<CarEntity> entitys = carService.findAll(param);
        List<CarEntityExcel> excelEntities = new ArrayList<>();
        for(CarEntity tempEntity :entitys){            
            CarEntityExcel excel = new CopyObjectEntity2EntityExcel<CarEntityExcel, CarEntity>().copy(CarEntityExcel.class,CarEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",CarEntityExcel.class, DateUtil.getID()+".xls",response);
    }
    @RequestMapping(value = "/car-check/{carId}")
    public PageData carCheck(@PathVariable("carId") String carId){
        carId = carId.trim();
        PageData result = new PageData();
        result.put("code", "-1");
        result.put("obj", null);
        result.put("car", carId.toUpperCase());

        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("carIdUnique", carId);
        List<CarEntity> all = carService.findAll(pd);
        if(1==all.size()){
            CarEntity carEntity = all.get(0);
            if(carEntity.getCarId().equals(carId)){
                result.put("code", "1");
                result.put("obj", carEntity);
                result.put("car", carEntity.getCarId());
            }
        }
        return result;
    }
    @RequestMapping("/car-ax-model/{ax}")
    public List<PageData> carAxModel(@PathVariable("ax") String ax) {
        List<PageData> list = new ArrayList<>();
        String arx2[] = new String[]{"载货汽车"};
        String arx3[] = new String[]{"载货汽车","中置轴挂车列车", "铰接列车"};
        String arx4[] = new String[]{"载货汽车","中置轴挂车列车", "铰接列车", "全挂汽车列车"};
        String arx5[] = new String[]{"铰接列车","中置轴挂车列车", "全挂汽车列车"};
        String arx6[] = new String[]{"铰接列车","中置轴挂车列车",  "全挂列车","罐罐车"};
        List<String> arxList = new ArrayList<>();
        if (ax.equals("2轴")) {
            arxList = Arrays.asList(arx2);
        }else if(ax.equals("3轴")){
            arxList = Arrays.asList(arx3);
        }else if(ax.equals("4轴")){
            arxList = Arrays.asList(arx4);
        }else if(ax.equals("5轴")){
            arxList = Arrays.asList(arx5);
        }else if(ax.equals("6轴")){
            arxList = Arrays.asList(arx6);
        }
        for (String str : arxList) {
            PageData pd = new PageData();
            if(str.equals("请选择")){
                pd.put("axes",0);
                pd.put("value", "-1");
                pd.put("name", str);
            }
            pd.put("axes", ax);
            pd.put("value", str);
            pd.put("name", str);
            list.add(pd);
        }
        return list;
    }
    @RequestMapping(value = "/car-info")
    public Map<String,String> carInfo(){
        PageData paramPd = this.getPageData();
        String name = "";
        if(null!=paramPd.get("flag")&&!"".equals(paramPd.get("flag").toString())){
            name = paramPd.get("flag").toString();
        }else{
            String ip = this.getRequest().getRemoteAddr();
            PageData pdConstant = new PageData();
            pdConstant.put("constantKey", "ip-location");
            pdConstant.put("constantValue", ip);
            List<SystemConstantEntity> all = systemConstantService.findAll(pdConstant);

            if(all.size()==1){
                name = all.get(0).getConstantValueDesc();
            }
        }
        String remote = url + "/" +getCar + "?name="+name;
        RemoteResult forObject = null;
        PageData rs = new PageData();
        try{
            forObject = this.restTemplate.getForObject(remote, RemoteResult.class);
            if (forObject.getCode()==1){
                String info = forObject.getMsg();
                rs.put("car", info);
            }
            else if(forObject.getCode()==-1){
                rs.put("car", "异常");
            }
        }catch (Exception e){
            rs.put("car", "异常");
        }
        return rs;
    }
}